<template>
  <div>
    <div>
      <header>
        <ye-tou></ye-tou>
      </header>
    </div>

    <div class="mystyle">
       <h1 style="color:black;">用户注册</h1>      
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
      <!-- 姓名 -->
       <el-form-item label="用户名" prop="userName">
          <el-input           
            v-model="ruleForm.userName" 
            placeholder="请填写用户名"  
            class="inputwidth"         
          ></el-input>
        </el-form-item>
        <!-- 年龄 -->
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="ruleForm.age"
          placeholder="请填写年龄" class="inputwidth"></el-input>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item label="电话" prop="phone">
                <el-input v-model="ruleForm.phone"
                placeholder="请填写电话"
                 class="inputwidth"></el-input>
              </el-form-item>
<!-- 身份证号 -->
            <el-form-item label="身份证号" prop="id_number">
              <el-input v-model="ruleForm.id_number"
                placeholder="请填写证件号码"  class="inputwidth"></el-input>
            </el-form-item>
<!-- 邮箱 -->
       <el-form-item label="邮箱" prop="email">
          <el-input           
            v-model="ruleForm.email"  
            placeholder="请填写邮箱"   class="inputwidth"              
          ></el-input>
        </el-form-item>
<!-- 密码 -->
        <el-form-item label="密码" prop="upwd">
          <el-input
            type="password"
            v-model="ruleForm.upwd"
            autocomplete="off"
            placeholder="请填写密码"  class="inputwidth"      
          ></el-input>
        </el-form-item>
<!-- 确认密码 -->
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
            placeholder="请确认密码"  class="inputwidth"      
          ></el-input>
        </el-form-item>
<!-- 性别 -->
<el-form-item label="称谓" prop="gender">
    <el-select v-model="ruleForm.gender" placeholder="请选择称谓">
      <el-option value="1" label="先生"></el-option>
      <el-option value="0" label="女士"></el-option>
    </el-select>
  </el-form-item>
  <!-- 随机验证码 -->
<el-row>
        <el-col :span="12">
          <el-form-item prop="code" label="验证码">
            <!-- <el-input type="text" v-model="ruleForm.code" auto-complete="off" placeholder="图形验证码" @keyup.enter.native="submitForm(ruleForm)"></el-input> -->
             <el-input type="text" v-model="ruleForm.code" auto-complete="off" placeholder="图形验证码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="code-box">
          <!-- <img :src="ruleForm.codeimg" alt="" class="codeimg" @click="getcode()"> -->
          <span v-html="ruleForm.codeimg" @click="getCode()" class="yanzheng"></span>
        </el-col>
      </el-row>
<!-- 提交框 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >注册</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import YeTou from "../components/YeTou.vue";

export default {
  components: {
    YeTou
  },
  name: 'login',
  data() {
    // 验证码自定义验证规则
    
    // 身份证号
    var isCardId = (rule, value, callback) => {
      if (!value) {
        return new Error("请输入身份证号)"); 
      } else {
       const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
        const card = reg.test(value);
        if (!card) {
          //判断座机为12位
          callback(new Error("身份证格式如:423024xxxx0216xxxx"));
        } else {
          callback();
        }
      }
};
    // 年龄
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 18) {
            callback(new Error("必须年满18岁"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.upwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var checkCode=(rule, value, callback)=>{
      console.log(value.toLowerCase(),this.answer.toLowerCase());
      if (value.toLowerCase()!==this.answer.toLowerCase()) {
        callback(new Error("验证码输入不正确"));
      }else{
        callback()
      }
    };
    var validateUserName=(rule, value, callback)=>{
      if (value.trim()) {
        let  obj=this.qs.stringify(this.ruleForm);
        this.$axios.post('/users/list/username',obj).then(res=>{
          // console.log('res',res);
          if (res.data.code) { 
            // console.log(res.msg);            
            callback(new Error(res.data.msg))
          }else{
            // console.log(res.msg);
            callback()
          }
        })
      }
    };
   var validatePhone=(rule, value, callback)=>{
      if (value.trim()) {
         let  obj=this.qs.stringify(this.ruleForm);
         this.$axios.post('/users/list/phone',obj).then(res=>{
          // console.log(res.data.code,typeof res.data.code);
           if (res.data.code) {
            //  console.log(res.msg);           
            callback(new Error(res.data.msg))
          }else{
            // console.log(res.msg);
             callback()
          }
        })
      }
    };
    return {
      logining: false,
      answer:'',
      // 接收参数
      ruleForm: {
        age:'',
        code: '',
        codeimg:'',
        id_number:"",
        gender: "",
        phone:"",
        userName:"",
        upwd: "",
        checkPass: "",
        // age: "",
      },
      // 规则      
      rules: {
        gender:[
            { required: true, message: '称谓不能为空', trigger: '' }
          ],
        code: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
        {validator:checkCode, trigger: "blur"
        }],
        // id_number:[
        //   { required: true, message: "请输入身份证号", trigger: "blur" },
        //   { validator: isCardId, trigger: "blur" }
        // ],
        phone:[{required: true,message: '手机号不能空',trigger: 'blur'},
        {pattern: /^1[3-9]\d{9}$/,message: '手机号格式不对',trigger: 'blur'},
        { validator: validatePhone, trigger: "blur" },
        ],
      //   email:[
      //     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      // { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      //   ],
        userName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
            { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
            { validator: validateUserName, trigger: "blur" },
          ],
        upwd: [{required: true,message: '密码不能空',trigger: 'blur'},{ validator: validatePass, trigger: "blur" }],
        checkPass: [{required: true,message: '确认密码不能空',trigger: 'blur'},{ validator: validatePass2, trigger: "blur" }],
        age: [{ validator: checkAge, trigger: "blur" }]        
      }
    };
  },


  // 创建完毕状态(里面是操作)
  created() {
    // 获取图形验证码
    this.getCode()
  },


  methods: {
    // 获取验证码
    getCode(){
      // console.log(`获取验证码`);
      this.$axios.get("/getCode").then(result=>{
      // console.log(result.data.text);
      this.answer=result.data.text;
      // console.log(typeof result.data);
      this.ruleForm.codeimg=result.data.data;
    })
    },


    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj={
              // code:this.ruleForm.code,       
              id_number:this.ruleForm.id_number,
              gender: this.ruleForm.gender=='先生'?1:0,
              phone:this.ruleForm.phone,
              userName:this.ruleForm.userName,
              upwd: this.ruleForm.upwd,
        // checkPass: this.ruleForm.,
          }
          obj=this.qs.stringify(obj);
          this.$axios.post("/users/register",obj).then(result=>{
            console.log("注册成功",result);
            // console.log(valid);
            // alert("注册成功");
            // console.log(`vip`,result.data.data[0].is_vip);
            // let flag=result.data.data[0].is_vip;
            // this.$router.push('/login')
             // 判断并且提示是否登录成功
            if (result.data.code){ // 注册成功
              // 弹窗提示登录成功
              this.$message({
                message: '注册成功',
                type:'success'
                // position: 'bottom',
                // duration: 3000
              })
               this.$router.replace("/login")
            }else{  // 注册失败
              this.$message.error('注册失败，请重试')
            }

          })          
        } else {
          console.log("注册失败!!");
          return false;
          }
      }
      );
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  
  }





</script>

<style>
.inputwidth {
  width: 400px;
}
.mystyle {
  padding: 3% 25%;
}
.yanzheng {
  display: inline-block;
   border-radius: 5px;
   margin-left: 20px;
   /* width: 11vw; */
  /* width: 100px; */
  /* height: 100px; */
  background-color: rgb(191, 207, 186);
  /* border: 2px solid block; */
}
</style>